package top.broncho.gank.ui.main

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.ui.*
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.jetbrains.anko.*
import reactivecircus.flowbinding.android.view.clicks
import top.broncho.gank.R
import top.broncho.gank.bean.UserInfoBody
import top.broncho.gank.constant.Constant
import top.broncho.gank.constant.KEY_SCORE
import top.broncho.gank.constant.REQUEST_CODE_LOGIN
import top.broncho.gank.databinding.ActivityMain1Binding
import top.broncho.gank.databinding.NavHeaderMain1Binding
import top.broncho.gank.ext.showToast
import top.broncho.gank.ui.activity.LoginActivity
import top.broncho.gank.ui.activity.MainViewModel
import top.broncho.gank.utils.Preference
import top.broncho.gank.utils.SettingUtil
import top.broncho.mvvm.base.BaseVMActivity

class MainActivity : BaseVMActivity<ActivityMain1Binding>() {
    private val viewModel by viewModels<MainViewModel> { viewModelFactory }
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var navHeader: NavHeaderMain1Binding

    /**
     * local username
     */
    private var username: String by Preference(Constant.USERNAME_KEY, "")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setSupportActionBar(binding.appBarMain.toolbar)

//        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
//        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_home, R.id.nav_score, R.id.nav_collect,
                R.id.nav_share, R.id.nav_todo, R.id.nav_setting
            ), binding.drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        binding.navView.setupWithNavController(navController)
        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            warn { "onDestinationChangedListener destination=$destination, controller=$controller" }
        }

        binding.navView.setNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.nav_score -> {
                    val score: Int = navHeader.tvUserRank.tag as Int
                    navController.navigate(
                        R.id.nav_score,
                        androidx.core.os.bundleOf(KEY_SCORE to score)
                    )
                    true
                }
                R.id.nav_logout -> {
                    alert(getString(R.string.confirm_logout), "退出") {
                        yesButton {
                            viewModel.logout()
                        }
                        noButton {}
                    }.show()
                }
                R.id.nav_night_mode -> {
                    if (SettingUtil.getIsNightMode()) {
                        SettingUtil.setIsNightMode(false)
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                    } else {
                        SettingUtil.setIsNightMode(true)
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                    }
                    window.setWindowAnimations(R.style.WindowAnimationFadeInOut)
                    recreate()
                }
                else -> {
                }
            }
            NavigationUI.onNavDestinationSelected(it, navController)
        }

        navHeader = NavHeaderMain1Binding.bind(binding.navView.getHeaderView(0))
        viewModel.userInfo.observe({ lifecycle }) {
            if (it.isFailure) {
                warn { "getUserInfo failed: ${it.exceptionOrNull()}" }
                return@observe
            }
            info { "getUserInfo: ${it.getOrNull()}" }
            showUserInfo(it.getOrNull()!!)
        }
        viewModel.logoutStatus.observe({ lifecycle }) {
            info { "logoutStatus changed: result=${it.getOrNull()}, exception=${it.exceptionOrNull()}" }
            showLogoutSuccess(it.isSuccess)
        }
        if (isLogin) {
            // 获取用户个人信息
            viewModel.getUserInfo()
            binding.navView.menu.findItem(R.id.nav_logout).isVisible = true
        } else {
            binding.navView.menu.findItem(R.id.nav_logout).isVisible = false
        }
        navHeader.ivCircleUser.clicks().onEach {
            if (isLogin) {
                navController.navigate(R.id.nav_rank)
            } else {
                toast(R.string.login_tint)
                startActivityForResult(Intent(this, LoginActivity::class.java), REQUEST_CODE_LOGIN)
            }
        }.launchIn(lifecycleScope)
    }

    private fun showLogoutSuccess(success: Boolean) {
        //mDialog.dismiss()
        if (success) {
            //CookieManager().clearAllCookies()
            Preference.clearPreference()
            showToast(resources.getString(R.string.logout_success))
            username = navHeader.tvUser.text.toString().trim()
            isLogin = false
            navHeader.tvUser.text = resources.getString(R.string.go_login)
            binding.navView.menu.findItem(R.id.nav_logout).isVisible = false
            //mHomeFragment?.lazyLoad()
            // 重置用户信息
            navHeader.tvUserRank.tag = null
            navHeader.tvUserRank.text = "排名: -- 积分: --"
        } else {
            toast("退出失败")
        }
    }

    private fun showUserInfo(bean: UserInfoBody) {
        navHeader.tvUser.text = username
        navHeader.tvUserRank.tag = bean.coinCount
        navHeader.tvUserRank.text = "排名: ${(bean.coinCount / 100 + 1)} 积分: ${bean.coinCount}"
        (binding.navView.menu.findItem(R.id.nav_score).actionView as TextView).apply {
            text = bean.coinCount.toString()
            gravity = Gravity.CENTER_VERTICAL
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        info { "onActivityResult: requestCode=$requestCode, resultCode=$resultCode" }
        if (requestCode == REQUEST_CODE_LOGIN) {
            if (resultCode == Activity.RESULT_OK) {
                navHeader.tvUser.text = username
                binding.navView.menu.findItem(R.id.nav_logout).isVisible = true
                //mHomeFragment?.lazyLoad()
                viewModel.getUserInfo()
            } else {
                navHeader.tvUser.text = resources.getString(R.string.go_login)
                binding.navView.menu.findItem(R.id.nav_logout).isVisible = false
                //mHomeFragment?.lazyLoad()
                // 重置用户信息
                navHeader.tvUserRank.tag = null
                navHeader.tvUserRank.text = "排名: -- 积分: --"
            }
        }
    }

    override fun isDisplayHomeAsUpEnabled() = false

    override fun getLayoutId() = R.layout.activity_main1
}
